
const Controller = require('../../core/Controller');
const query = require('../../core/db');


class userController extends Controller {
  constructor() {
    super();
  }
  async getPalaceList(ctx) {
    //const { mixnick, name, telephone, } = ctx.request.body || ctx.request.query;

    //查询宫殿信息
    let sql = 'select * from palace where 1=1';
    let values = [];
    let palace = await query(sql, values).then( results => { return results; });
    console.log('palace =====', palace);

    //异步查询对应宫殿的商品信息
    let promises = palace.map((item, index) => {
      let p_g_ids = item.p_g_ids || ''
      let value = p_g_ids.split(',');
      let zhanwei = [];
      for(let i=0; i<value.length; i++){ zhanwei.push('?'); }
      let sql = 'select * from goods where g_id in('+zhanwei.join()+')';
      return new Promise(( resolve, reject ) => {
        let res = query(sql, value).then( results => { return results; });
        resolve(res)
      });
    });
    let goods = await Promise.all(promises).then(res => {
      //console.log("========", res);
      return res
    });


    //添加宫殿商品列表
    for(let i=0; i<palace.length; i++) {
      palace[i].p_goodsList = goods[i];
    }
    //console.log(palace);
    ctx.response.body = palace;
  }

  async updatePalace(ctx) {
    const {
      p_id = '', p_peopleStart = '', p_peopleEnd = '', p_crowdStart = '', p_crowdEnd = ''
      } = ctx.request.body || ctx.request.query;
    //查询宫殿信息
   //console.log(qurey);
    if(p_id.length) {
      let zhanwei = [], values = [];
      if(p_peopleStart.length > 0) {
        zhanwei.push('p_peopleStart=?');values.push(p_peopleStart);
      }
      if(p_peopleEnd.length > 0) {
        zhanwei.push('p_peopleEnd=?');values.push(p_peopleEnd);
      }
      if(p_crowdStart.length > 0) {
        zhanwei.push('p_crowdStart=?');values.push(p_crowdStart);
      }
      if(p_crowdEnd.length > 0) {
        zhanwei.push('p_crowdEnd=?');values.push(p_crowdEnd);
      }
      let where = 'where p_id=?';
      values.push(p_id);
      let sql = `update palace set ${zhanwei.join()} ${where}`;
      console.log('sql', sql);
      console.log('values', values);
      let palace = await query(sql, values).then( results => { return results; });
      console.log('palace', palace);
      ctx.response.body = {
        succ: true,
        mess: {
          p_peopleStart,
          p_peopleEnd,
          p_crowdStart,
          p_crowdEnd
        }
      };
    } else {
      ctx.response.body = {
        succ: false,
        mess: 'p_id is not exist'
      };
    }
  }

  async addPalaceGoods(ctx) {
    const {
      p_id = '', goodsList = []
      } = ctx.request.body || ctx.request.query;
    //console.log(p_id, goodsList);

    if(p_id.length) {
      try {
        let goodsNumList = [], hasIndbGoods = [], hasNotindbGoods = [];
        goodsList.forEach(item => {
          goodsNumList.push(item.g_num)
        });

        //查询商品表中已存在的商品
        if(goodsNumList.length) {
          let values1 = goodsNumList;
          let zhanwei = [];
          goodsNumList.forEach(item => {
            zhanwei.push('?')
          });
          let sql1 = `SELECT * FROM goods WHERE g_num IN (${zhanwei.join()})`;
          let res1 = await query(sql1, values1).then( results => { return results; });
          //console.log('商品表中已存在的商品res', res1);
          goodsList.forEach((item, index) => {
            for(let i = 0; i<res1.length; i++){
              if(item.g_num == res1[i].g_num) {
                hasIndbGoods.push(res1[i]);
                return;
              }
            }
            hasNotindbGoods.push(item)
          });
          //console.log('商品表中已存在的商品hasIndbGoods', hasIndbGoods);
          //console.log('商品表中不存在的商品hasNotindbGoods', hasNotindbGoods);
        }


        //将商品表中不存在的商品添加到数据库
        let firstInsertId = 0;
        if(hasNotindbGoods.length) {
          let zhanwei2 = [];
          let values2 = [];
          hasNotindbGoods.forEach(item => {
            zhanwei2.push('(?,?,?,?)');
            values2.push(item.g_num);
            values2.push(item.g_title);
            values2.push(item.g_price);
            values2.push(item.g_imgUrl);
          });
          let sql2 = `INSERT INTO goods (g_num, g_title,g_price,g_imgUrl) VALUES ${zhanwei2.join()}`;
          //console.log('values2', values2);
          //console.log('sql2', sql2);
          let res2 = await query(sql2, values2).then( results => { return results; });
          firstInsertId = res2.insertId;
          //console.log('res2', res2.insertId);
        }


        //更新宫殿的商品列表
        const sql3 = `update palace set p_g_ids=? where p_id=?`;
        let p_g_ids = [];
        hasIndbGoods.forEach(item => {
          p_g_ids.push(item.g_id)
        });
        hasNotindbGoods.forEach((item, index) => {
          p_g_ids.push(parseInt(firstInsertId) + index)
        });
        const values3 = [p_g_ids.join(), p_id];
        //console.log('values3', values3);
        //console.log('sql3', sql3);
        const res3 = await query(sql3, values3).then( results => { return results; });
        //console.log('res3', res3);

        ctx.response.body = {
          succ: true
        }
      } catch (e) {
        console.log(e);
        ctx.response.body = {
          succ: false,
          mess: e
        };
      }
    } else {
      ctx.response.body = {
        succ: false,
        mess: 'p_id is not exist'
      };
    }
  }
}

module.exports = new userController;
